import _ from 'lodash'

export const treeConvertToArr = (tree: any[]) => {
  let arr: any[] = []
  const result: any[] = []
  arr = arr.concat(tree)
  while (arr.length) {
    const first = arr.shift() // 弹出第一个元素
    if (first.children) {
      // 如果有children
      arr = arr.concat(first.children)
      delete first.children
    }
    result.push(first)
  }
  return result
}

// 一维数组生成树结构数据
export const toTree = (
  arr: any = [],
  keyId = 'id',
  keyPid = 'parentId',
  children = 'children',
) => {
  const data = _.cloneDeep(arr)
  const tree: any = []
  for (let i = 0; i < data.length; i++) {
    const item: any = data[i]
    const parentId = item[keyPid]
    const parent: any = data.find((item: any) => item[keyId] === parentId)
    if (parent) {
      if (!parent[children]) {
        parent[children] = []
      }
      parent[children].push(item)
    } else {
      if (!item[children]) {
        item[children] = []
      }
      tree.push(item)
    }
  }
  return tree
}
/**
 *
 * @param size 文件大小
 * @returns
 */
export const formatFileSize = (size: number) => {
  if (size === 0) {
    return 0 + 'Bytes'
  }
  const unitArr = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
  let index = 0
  index = Math.floor(Math.log(size) / Math.log(1024))
  let value: any = size / Math.pow(1024, index)
  //  保留的小数位数
  value = value.toFixed(2)
  return value + ' ' + unitArr[index]
}
